package com.example.filepersistencetest

import android.content.Context
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.widget.Toast
import kotlinx.android.synthetic.main.activity_file_ioactivity.*
import java.io.*

class FileIOActivity : AppCompatActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_file_ioactivity)
        val inputtext = read("data")
        if(inputtext.isNotEmpty()){
            edittext.setText(inputtext)
            edittext.setSelection(inputtext.length)
            Toast.makeText(this, "Restore Succeeded", Toast.LENGTH_SHORT).show()
        }
    }

    override fun onDestroy() {
        super.onDestroy()
        val inputText = edittext.text.toString()
        save(inputText)
    }

    private fun save (text : String){
        try {
            val output = openFileOutput("data", Context.MODE_PRIVATE)
            val writer = BufferedWriter(OutputStreamWriter(output))
            //use ：在内部Lambda表达式执行完之后自动关闭外部流
            writer.use {
                it.write(text)
            }
        }
        catch (e : IOException){
            e.printStackTrace()
        }
    }

    private fun read (file:String) : String {
        val res = StringBuilder()
        try {
            val input = openFileInput(file)
            val reader = BufferedReader(InputStreamReader(input))
            reader.use{
                reader.forEachLine {
                    res.append(it)
                }
            }
        }catch (e: IOException){
            e.printStackTrace()
        }
        return res.toString()
    }
}